<template>
  <div>
    <van-dropdown-item title="区域" ref="item">
      <template #default>
        <van-picker
          ref="picker"
          :columns="columns"
          :show-toolbar="true"
          @confirm="onConfirm"
          @cancel="onCancel"
          class="picker-item"
          value-key="label"
        />
      </template>
    </van-dropdown-item>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import { queryHouseApi } from '@/api'
export default {
  name: 'Area',
  components: {},
  props: {},
  data() {
    return {
      columns: [],
      newArea: null,
      newSubway: null
    }
  },
  computed: {
    ...mapState(['queryParams'])
  },
  watch: {},
  created() {
    this.areaCondition()
  },
  methods: {
    ...mapMutations(['getQueryParams']),
    areaCondition() {
      const newArea = []
      const { area, subway } = this.$store.state.houseCondition
      newArea.push(area, subway)
      // console.log('newArea: ', newArea)
      this.columns = newArea
      // this.columns = this.addChildrenField(newArea)
      // 级联选择的数据嵌套深度需要保持一致，如果部分选项没有子选项，可以使用空字符串进行占位
      // 处理一下数据，修改children字段
      if (this.columns[0].children) {
        this.columns.forEach((obj) => {
          obj.children[0].children = [{ label: '不限', value: 'null' }]
        })
      }
    },
    onConfirm(val) {
      // console.log('确认', val)
      // 1、获取选中数据数组
      const res = this.$refs.picker.getValues()
      // 2、处理当选择区域时的情况
      if (res[0].value === 'area') {
        if (res[2].value !== 'null') {
          this.newArea = res[2].value
        } else if (res[1] !== 'null') {
          this.newArea = res[1].value
        }
        // console.log('区域：', this.newArea)
      } else {
        // 3、处理当选择地铁时的情况
        if (res[0].value === 'subway') {
          if (res[2].value !== 'null') {
            this.newSubway = res[2].value
          } else if (res[1] !== 'null') {
            this.newSubway = res[1].value
          }
        }
        // console.log('地铁：', this.newSubway)
      }
      //  4、发请求
      this.newAreaNetworkRequest()
      // 5、关闭下拉
      this.$refs.item.toggle(false)
    },
    onCancel() {
      this.$refs.item.toggle(false)
    },
    async newAreaNetworkRequest() {
      try {
        const obj = this.queryParams
        obj.area = this.newArea
        obj.subway = this.newSubway
        // 1、更新本地和vuex中复合请求条件
        this.getQueryParams(obj)
        // console.log('更新后的veux和本地查询条件', obj)
        //2、发请求
        this.$toast.loading({
          message: '加载中...',
          forbidClick: true
        })
        const { data } = await queryHouseApi(obj)
        // console.log(data.body.list)
        // 3、触发父组件事件将改变查询条件后重新申请得到的数据传出去，以便更新页面
        this.$emit('updateConditionFondHouse', data.body.list)
      } catch (err) {
        this.$toast.fail('加载失败，请重试')
      }
    }
  }
}
</script>

<style scoped></style>
